<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\Home\UserInfo;
use App\Models\Home\Weibo;
use Illuminate\Support\Facades\Session;

class LikeController extends Controller
{
    //点赞
    public function update($weibo_id)
    {
        //用户id
        $user_id = Session::get('user.id');
        //该微博点赞数+1
        Weibo::find($weibo_id)->increment('like_num');
        //取出用户已经点过赞的微博id
        $likes = UserInfo::find($user_id)->likes;
        //拼接当前微博id
        $likes .= ',' . $weibo_id;
        //更新likes字段
        UserInfo::find($user_id)->update(['likes' => $likes]);
    }

    //取消赞
    public function destroy($weibo_id)
    {
        //用户id
        $user_id = Session::get('user.id');
        //该微博点赞数-1
        Weibo::find($weibo_id)->decrement('like_num');
        //用户点过赞的微博id
        $likes = UserInfo::find($user_id)->likes;
        //转数组
        $likes_array = explode(',', $likes);
        //该微博id在数组中的位置
        $key = array_search($weibo_id, $likes_array);
        //从数组中删除该微博id
        array_splice($likes_array, $key, 1);
        //转字符串
        $likes = implode(',', $likes_array);
        //更新likes字段
        UserInfo::find($user_id)->update(['likes' => $likes]);
    }
}
